﻿using System.IO;
using FluentNHibernate;
using FluentNHibernate.Cfg;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using Sample.Persistence.Mappings;

namespace Sample.Persistence
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory != null) return _sessionFactory;
                _sessionFactory = Fluently.Configure(Configure()).BuildSessionFactory();
                return _sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        public static void GenerateSchema(bool outputScript)
        {
            new SchemaExport(Configure()).Execute(outputScript, true, false);
        }

        public static void WriteModels(DirectoryInfo directory)
        {
            if (!directory.Exists)
            {
                directory.Create();
                directory.Refresh();
            }

            var config = new Configuration().Configure();
            var model = new PersistenceModel();
            model.AddMappingsFromAssembly(typeof(PersonMap).Assembly);
            model.Configure(config);
            model.WriteMappingsTo(directory.Name);
        }

        public static Configuration Configure()
        {
            var cfg = new Configuration().Configure();
            Fluently.Configure(cfg).Mappings(m => m.FluentMappings.AddFromAssemblyOf<PersonMap>())
                .BuildConfiguration();
            return cfg;
        }
    }
}